/*
 * $Id: InfoStructureProxy.java 117 2009-07-02 10:32:28Z donbeave $
 */

package labour.manager.client.data;

import java.util.ArrayList;
import java.util.List;

import labour.concept.client.data.Locale;
import labour.concept.client.data.ObjectText;
import labour.concept.engine.client.data.EngineManager;
import labour.concept.engine.client.data.EngineObject;
import labour.concept.engine.client.data.Site;

import com.extjs.gxt.ui.client.data.DataProxy;
import com.extjs.gxt.ui.client.data.DataReader;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class InfoStructureProxy implements DataProxy<List<?>> {

  private EngineManager manager;

  public InfoStructureProxy(EngineManager manager) {
    this.manager = manager;
  }

  public void load(DataReader<List<?>> reader, final Object loadConfig, final AsyncCallback<List<?>> callback) {
    if (loadConfig == null) {
      callback.onSuccess(manager.getSites());
    }
    if (loadConfig instanceof Site) {
      callback.onSuccess(manager.getLocales());
    }
    if (loadConfig instanceof Locale) {
      manager.loadRootObjects(manager.getMainSite(), new AsyncCallback<List<EngineObject>>() {
        public void onFailure(Throwable caught) {
          callback.onFailure(caught);
        }

        public void onSuccess(List<EngineObject> result) {
          List<ObjectText> texts = new ArrayList<ObjectText>();

          for (EngineObject object : result) {
            if (object.hasData((Locale) loadConfig)) {
              texts.add(object.getData((Locale) loadConfig));
            }
          }

          callback.onSuccess(texts);
        }
      });
    }
    if (loadConfig instanceof ObjectText) {
      EngineObject object = (EngineObject) ((ObjectText) loadConfig).getObject();
      final Locale locale = ((ObjectText) loadConfig).getLocale();

      manager.loadObjectChildren(object, new AsyncCallback<List<EngineObject>>() {
        public void onFailure(Throwable caught) {
          callback.onFailure(caught);
        }

        public void onSuccess(List<EngineObject> result) {
          List<ObjectText> texts = new ArrayList<ObjectText>();

          for (EngineObject object : result) {
            if (object.hasData(locale)) {
              texts.add(object.getData(locale));
            }
          }

          callback.onSuccess(texts);
        }
      });
    }
  }

}
